package by.bsu.scs_bsu.filters;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import by.bsu.scs_bsu.logic.LoginLogic;
import by.bsu.scs_bsu.resources.managers.CookiesManager;
import by.bsu.scs_bsu.resources.managers.PageLinksManager;

public class LoginFilter implements Filter{
	
	//private FilterConfig filterConfig = null;
	private ServletContext servletContext = null;;

    private static final String PARAM_LINE = "?command=%s&user_name=%s&user_password=%s&remember_me=%s";
    private static final String COMMAND_LOGIN = "login";
    private static final String REMEMBER_ON = "on";
    
    private String user_name = null;
    private String user_password = null;
    private String remember_switch = null;

	public void init(FilterConfig config) throws ServletException {
		//this.filterConfig = config;
		servletContext = config.getServletContext();
	}
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain next) throws IOException, ServletException {
		Cookie [] cookies = ((HttpServletRequest)request).getCookies();
		if(cookies != null) {
			for(Cookie c: cookies) {
				if(CookiesManager.C_K_USER.equalsIgnoreCase(c.getName())) {
					user_name = c.getValue();
				} 
				if(CookiesManager.C_K_PASS.equalsIgnoreCase(c.getName())) {
					user_password = c.getValue();
				} 
				if(CookiesManager.C_K_SAVE.equalsIgnoreCase(c.getName())) {
					remember_switch = c.getValue();
				} 
			}
		}
		if(LoginLogic.checkLogin(user_name, user_password) && remember_switch != null && remember_switch.equalsIgnoreCase("true")) {
			String paramLine = String.format(PARAM_LINE, COMMAND_LOGIN, user_name, user_password, REMEMBER_ON);
			servletContext.getRequestDispatcher("/Controller" + paramLine).forward(request, response);
		} else {
			servletContext.getRequestDispatcher(PageLinksManager.getProperty(PageLinksManager.LOGIN_PAGE_PATH))
												.forward(request, response);
		}
	}
	
	public void destroy() {	
	}
}
